import time

import jwt

import App_setting as setting


def generate_jwt(*, payload: dict,
                 expiry: int = 0,
                 secret: str = setting.security.jwt_secret_key
                 ) -> str:
    _payload = {
        'jwt_mix_key': setting.security.jwt_mix_key,
        'jwt_dispatched_time': int(time.time()),
        'exp': expiry
    }
    _payload.update(payload)
    token = jwt.encode(_payload, key=secret, algorithm=setting.security.jwt_algorithm)

    return token


def decode_jwt(*, token, key=setting.security.jwt_secret_key):
    try:
        payload = jwt.decode(token, key, setting.security.jwt_algorithm)
        if payload['jwt_mix_key'] != setting.security.jwt_mix_key:
            return [400, 'JWT版本错误：MIX KEY 不一致']
        return [200, payload]
    except jwt.exceptions.ExpiredSignatureError:
        return [4001, '用户凭证过期，请重新登陆']
    except jwt.PyJWTError as e:
        print(e)
        return [4000, '用户凭证丢失或损毁，请重新登陆']
    except Exception as e:
        return [400, e]
